package com.ms.architecture.status

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.NetworkUtils

class NetworkStateManager(val callback: NetworkStateCallback) : DefaultLifecycleObserver {

    private val listener: NetworkUtils.OnNetworkStatusChangedListener =
        object : NetworkUtils.OnNetworkStatusChangedListener {
            override fun onConnected(networkType: NetworkUtils.NetworkType?) {
                isConnected = true
                callback.networkConnected()
            }

            override fun onDisconnected() {
                isConnected = false
                callback.networkDisconnected()
            }
        }
    private var isConnected: Boolean = true


    override fun onStart(owner: LifecycleOwner) {
        super.onStart(owner)
        NetworkUtils.registerNetworkStatusChangedListener(listener)
    }

    override fun onStop(owner: LifecycleOwner) {
        super.onStop(owner)
        NetworkUtils.unregisterNetworkStatusChangedListener(listener)
    }

    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        if (isConnected) {
            NetworkUtils.isAvailableAsync {
                when (it) {
                    true -> {
                        callback.networkAvailable()
                    }
                    false -> {
                        callback.networkUnAvailable()
                    }
                }
            }
        }
    }

    interface NetworkStateCallback {
        fun networkAvailable()
        fun networkUnAvailable()
        fun networkConnected()
        fun networkDisconnected()
    }
}